package com.cxs.netmanager.utils;

import com.cxs.netmanager.request.Response;
import ohos.app.Context;
import ohos.net.NetHandle;
import ohos.net.NetManager;
import ohos.net.NetStatusCallback;

import java.io.IOException;
import java.net.*;

class NetUtil {
    private Thread thread;

    public NetUtil(String urlString, ResponseCallBack callBack) {
        this.getData(urlString, callBack);
    }

    public String getData(String urlString, ResponseCallBack callBack) {
        this.thread = new Thread(new Runnable() {
            @Override
            public void run() {
                MyResponse response = getConnection(urlString);
                if (response.code == 200) {
                    callBack.onResponse(response);
                } else {
                    callBack.onFailure(response);
                }
            }
        });
        return null;
    }
    public  MyResponse getConnection(String urlString) {
        NetManager netManager = NetManager.getInstance(null);
        if (!netManager.hasDefaultNet()) {
            return null;
        }
        NetHandle netHandle = netManager.getDefaultNet();
        // 可以获取网络状态的变化
        NetStatusCallback callback = new NetStatusCallback() {

        };
        netManager.addDefaultNetStatusCallback(callback);
        HttpURLConnection connection = null;
        try {
            URL url = new URL(urlString);
            URLConnection urlConnection = netHandle.openConnection(url, Proxy.NO_PROXY);
            if (urlConnection instanceof HttpURLConnection) {
                connection = (HttpURLConnection)urlConnection;
            }
            connection.setRequestMethod("GET");
            connection.connect();
            return this.getResponse(connection);
        } catch (IOException e) {
            MyResponse myResponse = new MyResponse();
            myResponse.exception = e;
            return myResponse;
        }
    }

    private MyResponse getResponse(HttpURLConnection connection) throws IOException {
        MyResponse myResponse = new MyResponse();
        myResponse.code = connection.getResponseCode();
        myResponse.inputStream = connection.getInputStream();
        myResponse.errorStream = connection.getErrorStream();
        return myResponse;
    }

    void execute() {
        if (this.thread != null) {
            this.thread.start();
        }
    }
}
